import * as puppeteer from 'puppeteer'
import Locker from './locker'

const locker: Locker = new Locker(20)
let browser: puppeteer.Browser

async function getPage(): Promise<puppeteer.Page> {
  let page = await browser.newPage()
  page.on('close', () => {
    locker.release()
  })
  return page
}

export default {
  async newPage(): Promise<puppeteer.Page> {
    if (!browser) {
      browser = await puppeteer.launch()
    }
    await locker.lock()
    return getPage()
  }
}